package com.ez.supervise.test;

import java.sql.*;
import javax.naming.*;
import javax.sql.DataSource;

/*
 public class dbManager
 {
 public static synchronized Connection getConnection() throws Exception
 {
 try
 {
 Context initctx = new javax.naming.InitialContext();
 Context envctx = (Context)initctx.lookup("java:comp/env");
 DataSource ds = (DataSource)envctx.lookup("jdbc/Test");
 return ds.getConnection();
 }
 catch (Exception ex)
 {
 throw ex;
 }
 }	
 }
 */

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.sql.DataSource;

public class dbManager {

	final static private boolean VERBOSE = true; // 打印控制台控制

	// static Logger logger = Logger.getLogger(dbManager.class.getName());

	private Context initCtx = null;

	private Context ctx = null;

	private DataSource ds = null;

	private long timeout = 5000;

	public dbManager() {
		try {
			initCtx = new InitialContext();

			// init context，read config web.xml

			if (initCtx == null) {

				throw new Exception("Initial Failed!");

			}

			ctx = (Context) initCtx.lookup("java:comp/env");

			// find "jdbc/SqlServerDB" object this configruation in the
			// SERVER.XML of Tomcat

			if (ctx != null) {

				ds = (DataSource) ctx.lookup("jdbc/Test");

			}

			if (ds == null) {

				throw new Exception("Look up DataSource Failed!");

			}
		}

		catch (Exception e) {

			log(e, "Can’t get the Context!");

		}

	}

	public synchronized Connection getConnection() {

		// get connection and set to delay time

		long startTime = new java.util.Date().getTime();

		Connection con = null;

		while (con == null) {

			con = newConnection();

			if (con != null) {

				// log("Create New Connection!");

				break;

			}

			try {

				log("连接超时，重新连接，等待" + timeout + "ms");

				wait(timeout);

			}

			catch (InterruptedException e) {

				log(e, "连接超时!");

			}

			if ((new java.util.Date().getTime() - startTime) >= timeout) {

				log("Connection timeout!");

				break;

			}

		}
		return con;

	}

	private Connection newConnection() {

		Connection con = null;

		try {

			con = ds.getConnection();

			if (con == null) {

				throw new Exception("Create Connection Failed!");

			}

		}

		catch (Exception e) {

			log("Create Connection Failed!");

			System.out.println(e.getMessage());

		}

		return con;

	}

	public synchronized void freeConnection(Connection conn,

	Statement stmt,

	PreparedStatement pstmt) {

		try {

			// close Statement

			if (stmt != null) {

				stmt.close();

				stmt = null;

				// log("Close Statement......");

			}

			// close PreparedStatement

			if (pstmt != null) {

				pstmt.close();

				pstmt = null;

				// log("Close PreparedStatement......");

			}

		}

		catch (Exception e) {

			System.out.println(e.getMessage());

		}

		try {

			// close Connection

			if (conn != null) {

				conn.close();

				conn = null;

				// log("Close Connection......");

			}

		}

		catch (SQLException e) {

			log(e, "释放资源出错!");

		}

	}

	/************************************
	 * 
	 * write log file.
	 * 
	 * @param s
	 *            String
	 ************************************/

	private void log(String s) {

		if (VERBOSE) {

			System.out.println(new java.util.Date() + ":" + s);

			// logger.info(new java.util.Date()+s);

		}

	}

	private void log(Throwable e, String msg) {
		System.out.println(new java.util.Date() + ": " + msg);
	}

}
